/**
 * The front-end of the interface
 * does front-endy stuff
 * Luke Miller 1/28/15 
 */
package gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;

import sqlstuff.SQLManage;

public class DataTables extends JPanel {
	SQLManage SQL = new SQLManage();
	JTabbedPane tabbedPane;

	/**
	 * 
	 */
	public DataTables(SQLManage sql) {
		super(new GridLayout(1, 1));
		this.SQL = sql;
		this.tabbedPane = new JTabbedPane();

		JComponent analysis = getAnalysis();
		analysis.setPreferredSize(new Dimension(1800, 900));
		Icon icon = null;
		tabbedPane.addTab("Analysis", icon, analysis,
				"Farm Productivity Analysis");
		tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);

		JComponent panel1 = getData("Get Workers");

		panel1.setPreferredSize(new Dimension(900, 900));
		JComponent holdpanel1 = new JPanel();
		JComponent graphicspanel1 = getSmallPanel("Get Department Pay","Average Pay per Department");
		JButton addWorker = new JButton("Add Worker");
		WorkerButtonListener l = new WorkerButtonListener(SQL);
		addWorker.addActionListener(l);
		//set up graphicspanel1
		holdpanel1.add(addWorker);
		// set up graphicspanel1


		holdpanel1.add(panel1);
		holdpanel1.add(graphicspanel1);
		// panel1.setPreferredSize(new Dimension(900, 900));
		tabbedPane.addTab("Workers", icon, holdpanel1, "Worker Data");
		tabbedPane.setMnemonicAt(0, KeyEvent.VK_2);

		JComponent panel2 = getData("Get Animals");
		JComponent holdpanel2 = new JPanel();
		JComponent graphicspanel2 = new JPanel(new BorderLayout());

		JComponent smallgraphicspanel1 = getSmallPanel("Get Breed Health Data","Health per Breed");
		JComponent smallgraphicspanel2 = getSmallPanel("Get Purpose Health Data","Health per Purpose");
		JButton addAnimal = new JButton("Add Animal");
		AnimalButtonListener l1 = new AnimalButtonListener(sql);
		addAnimal.addActionListener(l1);
		
		//set up graphicspanel2
		graphicspanel2.add(smallgraphicspanel1, BorderLayout.NORTH);
		graphicspanel2.add(smallgraphicspanel2, BorderLayout.SOUTH);

		holdpanel2.add(addAnimal);
		holdpanel2.add(panel2);
		holdpanel2.add(graphicspanel2);
		panel2.setPreferredSize(new Dimension(900, 900));
		tabbedPane.addTab("Animals", icon, holdpanel2, "Animal Data");
		tabbedPane.setMnemonicAt(1, KeyEvent.VK_3);

		JComponent panel3 = getData("Get Fields");
		JComponent holdpanel3 = new JPanel();
		// String[] args={"0"};
		JComponent graphicspanel3 = new JPanel(new BorderLayout());
		JComponent smallgraphicspanel3= getSmallPanel("Get Field Data","Workers in Each Field");
		JComponent smallgraphicspanel4= getSmallPanel("Get Empty Fields","Fields Without Workers");
		JButton addField = new JButton("Add Field");
		FieldButtonListener l2 = new FieldButtonListener(SQL);
		addField.addActionListener(l2);
		//set up graphicspanel3
		graphicspanel3.add(smallgraphicspanel3, BorderLayout.NORTH);
		graphicspanel3.add(smallgraphicspanel4, BorderLayout.SOUTH);

		holdpanel3.add(addField);


		holdpanel3.add(panel3);
		holdpanel3.add(graphicspanel3);
		panel3.setPreferredSize(new Dimension(900, 900));
		tabbedPane.addTab("Fields", icon, holdpanel3, "Field Data");
		tabbedPane.setMnemonicAt(2, KeyEvent.VK_4);

		JComponent panel4 = getData("Get Pastures");
		JComponent holdpanel4 = new JPanel();
		JComponent graphicspanel4 = new JPanel();//getSmallPanel("","");
		//set up graphicspanel4
		JButton addPasture = new JButton("Add Pasture");
		PastureButtonListener l3 = new PastureButtonListener(SQL);
		addPasture.addActionListener(l3);

		holdpanel4.add(addPasture);

		holdpanel4.add(panel4);
		holdpanel4.add(graphicspanel4);
		panel4.setPreferredSize(new Dimension(900, 900));
		tabbedPane.addTab("Pastures", icon, holdpanel4, "Pasture Data");
		tabbedPane.setMnemonicAt(3, KeyEvent.VK_5);

		// Add the tabbedPane to this panel.
		add(tabbedPane);

		// The following line enables to use scrolling tabs.
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
	}

	private JScrollPane getData(String stmt) {
		String[] emptyargs = {};
		return getData(stmt, emptyargs);
		/*
		 * ResultSet rs = SQL.executeSprocNoParams(stmt);
		 * 
		 * try { DefaultTableModel model = buildTableModel(rs); JTable table =
		 * new JTable(model); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		 * for (int column = 0; column < table.getColumnCount(); column++) {
		 * TableColumn tableColumn = table.getColumnModel().getColumn( column);
		 * String header = (String) tableColumn.getHeaderValue(); int
		 * preferredWidth = header.length() * 15;// modification to // account
		 * for // header width int maxWidth = tableColumn.getMaxWidth();
		 * 
		 * for (int row = 0; row < table.getRowCount(); row++) {
		 * TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
		 * Component c = table.prepareRenderer(cellRenderer, row, column); int
		 * width = c.getPreferredSize().width +
		 * table.getIntercellSpacing().width; preferredWidth =
		 * Math.max(preferredWidth, width);
		 * 
		 * // We've exceeded the maximum width, no need to check other // rows
		 * 
		 * if (preferredWidth >= maxWidth) { preferredWidth = maxWidth; break; }
		 * }
		 * 
		 * tableColumn.setPreferredWidth(preferredWidth); }// Column resizing
		 * modified from: //
		 * https://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
		 * table.setRowSorter(new TableRowSorter<>(model)); JScrollPane ret =
		 * new JScrollPane(table); return ret; } catch (SQLException e) {
		 * e.printStackTrace(); } return null;
		 */
	}

	private JScrollPane getData(String stmt, String[] args) {
		ResultSet rs = SQL.executeSprocWithParams(stmt, args);

		try {
			// System.out.println("Table being made?");
			DefaultTableModel model = buildTableModel(rs);
			JTable table = new JTable(model);
			Listener l = new Listener(table, SQL);
			table.getModel().addTableModelListener(l);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			for (int column = 0; column < table.getColumnCount(); column++) {
				TableColumn tableColumn = table.getColumnModel().getColumn(
						column);
				String header = (String) tableColumn.getHeaderValue();
				int preferredWidth = header.length() * 15;// modification to
															// account for
															// header width
				int maxWidth = tableColumn.getMaxWidth();

				for (int row = 0; row < table.getRowCount(); row++) {
					TableCellRenderer cellRenderer = table.getCellRenderer(row,
							column);
					Component c = table.prepareRenderer(cellRenderer, row,
							column);
					int width = c.getPreferredSize().width
							+ table.getIntercellSpacing().width;
					preferredWidth = Math.max(preferredWidth, width);

					// We've exceeded the maximum width, no need to check other
					// rows

					if (preferredWidth >= maxWidth) {
						preferredWidth = maxWidth;
						break;
					}
				}

				tableColumn.setPreferredWidth(preferredWidth);
			}// Column resizing modified from:
				// https://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
			table.setRowSorter(new TableRowSorter<>(model));
			JScrollPane ret = new JScrollPane(table);
			return ret;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// protected JComponent makeTextPanel(String text) {
	// JPanel panel = new JPanel(false);
	// JLabel filler = new JLabel(text);
	// filler.setHorizontalAlignment(JLabel.CENTER);
	// panel.setLayout(new GridLayout(1, 1));
	// panel.add(filler);
	// return panel;
	// }

	private DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {

		ResultSetMetaData metaData = rs.getMetaData();

		// names of columns
		Vector<String> columnNames = new Vector<String>();
		int columnCount = metaData.getColumnCount();
		for (int column = 1; column <= columnCount; column++) {
			columnNames.add(metaData.getColumnName(column));
		}

		// data of the table
		Vector<Vector<Object>> data = new Vector<Vector<Object>>();
		while (rs.next()) {
			Vector<Object> vector = new Vector<Object>();
			for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
				vector.add(rs.getObject(columnIndex));
			}
			data.add(vector);
		}

		DefaultTableModel t = new DefaultTableModel(data, columnNames);

		return t;

	}

	private JComponent getAnalysis() {
		JPanel tPanel = new JPanel();
		tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.PAGE_AXIS));
		tPanel.add(getSmallPanel("Get Idle Pasture Data", "Unused Pastures"));
		tPanel.add(getSmallPanel("Get Feed Usage", "Feed Usage"));
		tPanel.add(getSmallPanel("Get Herd Data", "Herds"));
		tPanel.add(getSmallPanel("Get Department Data", "Departments"));
		tPanel.add(getSmallPanel("Get Shift Data", "Workers Per Shift"));
		tPanel.add(getSmallPanel("Get Manager Data", "Employees per Manager"));
		return tPanel;
	}

	private JPanel getSmallPanel(String sproc, String title) {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
		panel.setPreferredSize(new Dimension(800, 200));
		JTextArea pastureTitle = new JTextArea(title);
		pastureTitle.setEditable(false);
		pastureTitle.setMaximumSize(new Dimension(title.length() * 11, 20));
		panel.add(pastureTitle);
		JScrollPane data = getData(sproc);
		data.setMaximumSize(new Dimension(800, 200));
		panel.add(data);
		return panel;

	}

	private JPanel getSmallPanel(String sproc, String[] args, String title) {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
		panel.setPreferredSize(new Dimension(800, 200));
		JTextArea pastureTitle = new JTextArea(title);
		pastureTitle.setEditable(false);
		pastureTitle.setMaximumSize(new Dimension(200, 20));
		panel.add(pastureTitle);
		JScrollPane data = getData(sproc, args);
		data.setMaximumSize(new Dimension(800, 200));
		panel.add(data);
		return panel;

	}

}
